const { default: axios } = require("axios");
const Koa = require('koa2');
const fs = require('fs').promises;
const { url } = require("../router");
const app = new Koa()
const path = require('path')
const { createNews} = require("../service/newsContentserver");
const { log } = require("console");
class Upload {
    // 添加临时图片文件
    async addtemp(ctx, next) {
        const { custom } = ctx.request.files
        ctx.body = {
            errno: 0,
            data: [{
                url: `http://127.0.0.1:3003/${custom.newFilename}`
            }],
        }
    }
    // 上传视频文件
    async tempvideo(ctx, next) {
        const { custom } = ctx.request.files
       
        ctx.body = {
            errno: 0,
            "data": {
                "url":`http://127.0.0.1:3003/${custom.newFilename}`, // 视频 src ，必须
                "poster": "xxx.png" // 视频封面图片 url ，可选
            }
        }
    }
    // 保存编辑 对比照片  对比视频  标题   内容
    async saveEdits(ctx, next) {
        // 检查对比图片/视频 删除临时图片
        const { imageUrl,videoUrl,msgData,htmlData} = ctx.request.body
        // console.log(imageUrl,videoUrl,msgData,htmlData, 222)
        const newImageUrlArr = []; // 修正拼写
        const newVideoUrlArr=[];
        // 使用 forEach 来填充 newImageUrlArr
        imageUrl.forEach(url => {
            // 提取文件名和扩展名
            const fileName = url.substring(url.lastIndexOf('/') + 1);
            newImageUrlArr.push(fileName);
        });
        videoUrl.forEach(url => {
            // 提取文件名和扩展名
            const fileName = url.substring(url.lastIndexOf('/') + 1);
            newVideoUrlArr.push(fileName);
        });
     let  imageVideoData=[...newImageUrlArr,...newVideoUrlArr]
        const folderPath = path.join(__dirname, '../upload'); // 文件夹路径
        try {
            // 遍历文件名数组，删除每个文件
            await Promise.all(imageVideoData.map(async (fileName) => {
              const filePath = path.join(folderPath, fileName); // 拼接完整路径
              await fs.unlink(filePath); // 删除文件
            //   console.log(`Deleted file: ${filePath}`);
            }));
            let newConten={...msgData,content:htmlData}
            // console.log(newConten,2323)
                const res = await createNews(newConten)
            ctx.body = {
              success: true,
              message: "咨询上传成功",
            };
          } catch (error) {
            console.error('Error deleting files:', error);
            ctx.status = 500; // 500 错误
            ctx.body = {
              success: false,
              message: 'Failed to delete files.',
            };
          }
    }
}

module.exports = new Upload();